//
//  EScrollerView.m
//  Everest
//
//  Created by 李其昌 on 14/12/17.
//  Copyright (c) 2014年 ThreeL. All rights reserved.
//

#import "EScrollerView.h"
#import "UIImageView+WebCache.h"
#define kImageChangeTime 5.0f
@implementation EScrollerView
@synthesize delegate;

- (void)dealloc {
    
	[_scrollView release];
    [_noteTitle release];
	delegate = nil;
    if (_pageControl) {
        [_pageControl release];
    }
    if (_imageArray) {
        [_imageArray release];
        _imageArray = nil;
    }
    if (_titleArray) {
        [_titleArray release];
        _titleArray = nil;
    }
    [super dealloc];
}
- (id)initWithFrameRect:(CGRect)rect ImageArray:(NSArray *)imgArr TitleArray:(NSArray *)titArr
{
    
	if ((self = [super initWithFrame:rect])) {
        self.userInteractionEnabled = YES;
        // 设置本页面数组对titArr的引用计数+1
        self.titleArray = [titArr retain];
        // 定义一个交换数组, 将imgArr的赋给交换数组
        NSMutableArray *tempArray = [NSMutableArray arrayWithArray:imgArr];
        // 在数组头插入一张尾的图片
        [tempArray insertObject:[imgArr objectAtIndex:([imgArr count] - 1)] atIndex:0];
        // 在数组中添加一张最后一张图
        [tempArray addObject:[imgArr objectAtIndex:0]];
        
		self.imageArray = [[NSArray arrayWithArray:tempArray] retain];
		viewSize = rect;
        NSUInteger pageCount = [self.imageArray count];
        self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, viewSize.size.width, viewSize.size.height)];
        self.scrollView.pagingEnabled = YES;
        self.scrollView.contentSize = CGSizeMake(viewSize.size.width * pageCount, viewSize.size.height);
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.scrollsToTop = NO;
        self.scrollView.delegate = self;
        for (int i = 0; i < pageCount; i++) {
            NSString *imgURL = [self.imageArray objectAtIndex:i];
            UIImageView *imgView = [[[UIImageView alloc] init] autorelease];
            if ([imgURL hasPrefix:@"http://"]) {
                //网络图片 请使用ego异步图片库
                [imgView setImageWithURL:[NSURL URLWithString:imgURL]];
            } else {
                UIImage *img = [UIImage imageNamed:[self.imageArray objectAtIndex:i]];
                [imgView setImage:img];
            }
            
            [imgView setFrame:CGRectMake(viewSize.size.width * i , 0,viewSize.size.width, viewSize.size.height)];
            imgView.tag = i;
            UITapGestureRecognizer *Tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imagePressed:)] autorelease];
            [Tap setNumberOfTapsRequired:1];
            [Tap setNumberOfTouchesRequired:1];
            imgView.userInteractionEnabled = YES;
            [imgView addGestureRecognizer:Tap];
            [self.scrollView addSubview:imgView];
        }
        [self.scrollView setContentOffset:CGPointMake(viewSize.size.width, 0)];
        [self addSubview:self.scrollView];

        
        
        //说明文字层
        UIView *noteView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 33,self.bounds.size.width,33)];
        noteView.backgroundColor = [UIColor clearColor];
        float pageControlWidth = (pageCount - 2) * 10.0f + 40.f;
        float pagecontrolHeight = 20.0f;
        self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake((self.frame.size.width - pageControlWidth),6, pageControlWidth, pagecontrolHeight)];
        self.pageControl.currentPage = 0;
        self.pageControl.numberOfPages = (pageCount - 2);
        [noteView addSubview:self.pageControl];
        
        self.noteTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 6, self.frame.size.width - pageControlWidth - 15, 20)];
        [self.noteTitle setText:[self.titleArray objectAtIndex:0]];
        [self.noteTitle setBackgroundColor:[UIColor clearColor]];
        [self.noteTitle setFont:[UIFont systemFontOfSize:13]];
        [noteView addSubview:self.noteTitle];
        
        [self addSubview:noteView];
        [noteView release];
	}
//    [self delayCall];
    [self addTimer];
	return self;
}

- (void)delayCall
{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:kImageChangeTime target:self selector:@selector(scrollToNextPage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
    
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeTimer];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addTimer];
}

-(void)removeTimer
{
    [self.timer invalidate];
}

-(void)addTimer
{
    self.timer=[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(scrollToNextPage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)scrollToNextPage
{
    [UIView beginAnimations:nil context:nil];
    NSInteger pageNum = self.pageControl.currentPage;
    CGRect rect = CGRectMake((pageNum + 2) * self.bounds.size.width, 0, self.bounds.size.width, self.scrollView.bounds.size.height);
    [self.scrollView scrollRectToVisible:rect animated:NO];
    pageNum++;
    if (pageNum == self.imageArray.count) {
        CGRect newRect=CGRectMake(self.bounds.size.width, 0, self.bounds.size.width, self.scrollView.bounds.size.height);
        [self.scrollView scrollRectToVisible:newRect animated:NO];
    }
    if (currentPageIndex == 0) {
        [self.scrollView setContentOffset:CGPointMake(([self.imageArray count] - 2) * viewSize.size.width, 0)];
    } else if (currentPageIndex == ([self.imageArray count] - 1)) {
        [self.scrollView setContentOffset:CGPointMake(viewSize.size.width, 0)];
    }
    
    [UIView setAnimationDuration:5];
    [UIView commitAnimations];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    CGFloat pageWidth = self.scrollView.frame.size.width;
    int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    currentPageIndex = page;
       
    self.pageControl.currentPage = (page - 1);
    int titleIndex = page - 1;
    if (titleIndex == [self.titleArray count]) {
        titleIndex = 0;
    }
    if (titleIndex < 0) {
        titleIndex = (int)[self.titleArray count] - 1;
    }
    if (self.titleArray.count != 0) {
        [self.noteTitle setText:[self.titleArray objectAtIndex:titleIndex]];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (currentPageIndex == 0) {
        [self.scrollView setContentOffset:CGPointMake(([self.imageArray count] - 2) * viewSize.size.width, 0)];
    } else if (currentPageIndex == ([self.imageArray count] - 1)) {
        [self.scrollView setContentOffset:CGPointMake(viewSize.size.width, 0)];
    }

}
- (void)imagePressed:(UITapGestureRecognizer *)sender
{

    if ([delegate respondsToSelector:@selector(EScrollerViewDidClicked:)]) {
        [delegate EScrollerViewDidClicked:sender.view.tag];
    }
}

@end
